package it.ap.sa.core.dao.util;

import java.io.Serializable;
import java.time.LocalDateTime;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import it.ap.sa.core.utils.AuthUtils;

/**
 *
 */
public class ActivityTrackerInterceptor extends EmptyInterceptor {

	private static final long serialVersionUID = 1L;
	
	@SuppressWarnings("unused")
	private String operation = "INSERT";
	
	boolean isMainEntity = false;

	// called when record deleted.
	public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		operation = "DELETE";
		isMainEntity = true;
		System.out.println("Delete function called");
	}

	// called when record updated
	public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
		if (entity instanceof UserDateModel || entity instanceof DateModel) {
			operation = "UPDATE";
			isMainEntity = true;

			for (int i = 0; i < propertyNames.length; i++) {
				if ("usermod".equals(propertyNames[i])) {
					currentState[i] = AuthUtils.getLoggedUsername();
				}
				if ("datemod".equals(propertyNames[i])) {
					currentState[i] = LocalDateTime.now();
				}
			}
			return true;
		}
		isMainEntity = false;
		return false;
	}

	// called when record insert
	public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		if (entity instanceof UserDateModel || entity instanceof DateModel) {
			operation = "INSERT";
			isMainEntity = true;

			for (int i = 0; i < propertyNames.length; i++) {
				if ("userins".equals(propertyNames[i])) {
					state[i] = AuthUtils.getLoggedUsername();
				}
				if ("dateins".equals(propertyNames[i])) {
					state[i] = LocalDateTime.now();
				}
			}

			return true;
		}
		isMainEntity = false;
		return false;
	}
}